package com.jswlw.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageUtils {

    public static Logger logger = LoggerFactory.getLogger(ImageUtils.class);

    //public static String ROOT = "D:/";

    public static String ROOT = "/home/zhaome/";

    public static String FX1_BACK = ROOT + "upload/fx1.jpg";

    public static String FX2_BACK = ROOT + "upload/fx2.jpg";

    public static String FX3_BACK = ROOT + "upload/fx3.jpg";

    /**
     * 根据底板生成图片
     *
     * @return
     * @throws Exception
     */
    public static String fx1(String themeName, String photo, String wxCode) {
        try {
            BufferedImage image = ImageIO.read(new FileInputStream(FX1_BACK));
            Graphics2D gd2 = (Graphics2D) image.getGraphics();
            ImageIcon photoIcon = new ImageIcon(convertCircular(netImage(photo)));
            gd2.drawImage(photoIcon.getImage(), 315, 175, 120, 120, null);
            gd2.setColor(Color.white);
            Font font1 = new Font("黑体", Font.BOLD, 30);
            gd2.setFont(font1);
            FontMetrics metrics = gd2.getFontMetrics(font1);

            int x1 = 0 + (image.getWidth() - metrics.stringWidth(themeName)) / 2;
            gd2.drawString(themeName, x1, 355);
            Font font2 = new Font("黑体", Font.BOLD, 40);
            gd2.setFont(font2);
            FontMetrics metrics2 = gd2.getFontMetrics(font2);
            int x2 = 0 + (image.getWidth() - metrics2.stringWidth("看看你们的手气如何")) / 2;
            gd2.drawString("看看你们的手气如何", x2, 420);
            gd2.drawImage(convertCircular(netImage(wxCode)), 255, 500, 240, 240, null);

            String realPath = "upload/temp/" + UUIDUtils.uuid32() + ".jpg";
            OutputStream outputStream = new FileOutputStream(new File(ROOT + realPath));
            ImageIO.write(image, "JPG", outputStream);
            outputStream.close();
            return realPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 根据底板生成图片
     *
     * @return
     * @throws Exception
     */
    public static String fx2(String content, String photo1, String photo2) {
        try {
            BufferedImage image = ImageIO.read(new FileInputStream(FX2_BACK));
            Graphics2D gd2 = (Graphics2D) image.getGraphics();

            ImageIcon imageIcon1 = new ImageIcon(convertCircular(netImage(photo1)));
            gd2.drawImage(imageIcon1.getImage(), (image.getWidth() / 2 - 120) / 2, 50, 120, 120, null);

            ImageIcon imageIcon2 = new ImageIcon(convertCircular(netImage(photo2)));
            gd2.drawImage(imageIcon2.getImage(), ((int) (image.getWidth() * 1.5) - 120) / 2, 50, 120, 120, null);


            gd2.setColor(Color.red);
            Font font = new Font("黑体", Font.BOLD, 100);
            gd2.setFont(font);
            FontMetrics metrics0 = gd2.getFontMetrics(font);
            int x = 0 + (image.getWidth() - metrics0.stringWidth("VS")) / 2;
            gd2.drawString("VS", x, 160);

            gd2.setColor(Color.black);
            Font font1 = new Font("黑体", Font.BOLD, 40);
            gd2.setFont(font1);
            FontMetrics metrics = gd2.getFontMetrics(font1);
            int x1 = 0 + (image.getWidth() - metrics.stringWidth(content)) / 2;

            gd2.drawString(content, x1, 350);
            int x2 = 0 + (image.getWidth() - metrics.stringWidth("看看你们的手气如何")) / 2;
            gd2.drawString("看看你们的手气如何", x2, 400);

            String realPath = "upload/temp/" + UUIDUtils.uuid32() + ".JPG";
            OutputStream outputStream = new FileOutputStream(new File(ROOT + realPath));
            ImageIO.write(image, "JPG", outputStream);
            outputStream.close();
            return realPath;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return "";
    }

    /**
     * 根据底板生成图片
     *
     * @return
     * @throws Exception
     */
    public static String fx4(String photo1, String photo2) {
        try {
            String content = "我在找TA,大家一起帮我找！";
            BufferedImage image = ImageIO.read(new FileInputStream(FX2_BACK));
            Graphics2D gd2 = (Graphics2D) image.getGraphics();

            ImageIcon imageIcon1 = new ImageIcon(convertCircular(netImage(photo1)));
            gd2.drawImage(imageIcon1.getImage(), (image.getWidth() / 2 - 120) / 2, 50, 120, 120, null);

            ImageIcon imageIcon2 = new ImageIcon(convertCircular(netImage(photo2)));
            gd2.drawImage(imageIcon2.getImage(), ((int) (image.getWidth() * 1.5) - 120) / 2, 50, 120, 120, null);


            gd2.setColor(Color.red);
            Font font = new Font("黑体", Font.BOLD, 100);
            gd2.setFont(font);
            FontMetrics metrics0 = gd2.getFontMetrics(font);
            int x = 0 + (image.getWidth() - metrics0.stringWidth("VS")) / 2;
            gd2.drawString("VS", x, 160);

            gd2.setColor(Color.black);
            Font font1 = new Font("黑体", Font.BOLD, 40);
            gd2.setFont(font1);
            FontMetrics metrics = gd2.getFontMetrics(font1);
            int x1 = 0 + (image.getWidth() - metrics.stringWidth(content)) / 2;

            gd2.drawString(content, x1, 350);
            int x2 = 0 + (image.getWidth() - metrics.stringWidth("看看你们的手气如何")) / 2;
            gd2.drawString("看看你们的手气如何", x2, 400);

            String realPath = "upload/temp/" + UUIDUtils.uuid32() + ".JPG";
            OutputStream outputStream = new FileOutputStream(new File(ROOT + realPath));
            ImageIO.write(image, "JPG", outputStream);
            outputStream.close();
            return realPath;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return "";
    }

    /**
     * 根据底板生成图片
     *
     * @return
     * @throws Exception
     */
    public static String fx3(String themeName, String photo, String roomSn) {
        try {
            logger.info(themeName);
            logger.info(roomSn);
            BufferedImage image = ImageIO.read(new FileInputStream(FX3_BACK));
            Graphics2D gd2 = (Graphics2D) image.getGraphics();
            ImageIcon imageIcon = new ImageIcon(convertCircular(netImage(photo)));

            gd2.drawImage(imageIcon.getImage(), (image.getWidth() - 120) / 2, 40, 120, 120, null);

            gd2.setColor(Color.white);
            Font font1 = new Font("黑体", Font.BOLD, 50);
            gd2.setFont(font1);
            FontMetrics metrics1 = gd2.getFontMetrics(font1);
            int x1 = 0 + (image.getWidth() - metrics1.stringWidth(themeName)) / 2;
            gd2.drawString(themeName, x1, 350);

            gd2.setColor(Color.white);
            Font font2 = new Font("黑体", Font.BOLD, 50);
            gd2.setFont(font2);
            FontMetrics metrics2 = gd2.getFontMetrics(font2);
            int x2 = 0 + (image.getWidth() - metrics2.stringWidth("房间号:" + roomSn)) / 2;
            gd2.drawString("房间号:" + roomSn, x2, 450);
            String realPath = "upload/temp/" + UUIDUtils.uuid32() + ".JPG";
            OutputStream outputStream = new FileOutputStream(new File(ROOT + realPath));
            ImageIO.write(image, "JPG", outputStream);
            outputStream.close();
            return realPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String netImage(String netUrl) throws Exception {
        String realPath = "/home/zhaome/upload/temp/";
        String fileName = realPath + UUIDUtils.uuid32() + ".jpg";
        URL url = new URL(netUrl);
        //打开链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(inStream);
        //new一个文件对象用来保存图片，默认保存当前工程根目录
        File imageFile = new File(fileName);
        //创建输出流
        FileOutputStream outStream = new FileOutputStream(imageFile);
        //写入数据
        outStream.write(data);
        //关闭输出流
        outStream.close();

        return fileName;
    }

    public static BufferedImage convertCircular(String inputFile) throws IOException {
        Image src = ImageIO.read(new File(inputFile));
        BufferedImage bi1 = (BufferedImage) src;

        //透明底的图片
        BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());
        Graphics2D g2 = bi2.createGraphics();
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2.drawImage(bi1, 0, 0, null);
        //设置颜色
        g2.setBackground(Color.green);
        g2.dispose();
        return bi2;
    }

    public static BufferedImage makeRoundedCornerImg(String inputFile,
                                                     int cornerRadius) throws IOException {
        BufferedImage image = ImageIO.read(new File(inputFile));

        int w = image.getWidth();
        int h = image.getHeight();
        BufferedImage output = new BufferedImage(w, h,
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = output.createGraphics();

        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius,
                cornerRadius));

        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(image, 0, 0, null);

        g2.dispose();
        return output;
//        String filetype = tfile.substring(tfile.lastIndexOf(".")+1);
//        try {
//            ImageIO.write(output, filetype, new File(tfile));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    public static void main(String[] args) {
        String photo = "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83erczUVf0FKRREU3dXc3pEQkyrqB3PSPLJCVdoyg1fzZnOFuibbgcicBXUUdsLq2q6wRqxDufjfFy0hA/0";
        ImageUtils.fx3("我找到了他，赢得了50元奖励", photo, "201051");
    }
}
